<template>
    <!-- 事实外包方查看页面 -->
    <div class="e-form">
        <div class="tabs" v-if="Object.keys(formData).length != 0">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <!-- 基本信息 -->
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="委托人"
                    name="client"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="accessory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">基本信息</div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        :model="formData"
                                        label-width="150px"
                                        ref="formData"
                                    >
                                    <BillTop title="事实外包方变更详情" @cancel="handleClose"></BillTop>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="统一社会信用代码"
                                                >
                                                    {{ formData.creditCode }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="外包方类别"
                                                >
                                                    {{
                                                        formData.type == 0
                                                            ? '分包商'
                                                            : '供应商'
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="外包方名称："
                                                >
                                                    {{ formData.outerName }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="法人代表">
                                                    {{ formData.deputy }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="法人身份证号码："
                                                >
                                                    {{ formData.idCard }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="法人身份证附件"
                                                >
                                                    <span
                                                        @click="preview2()"
                                                        style="
                                                            color: blue;
                                                            cursor: pointer;
                                                            overflow: hidden;
                                                        "
                                                    >
                                                        {{
                                                            formData.deputyOssName
                                                        }}
                                                    </span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="注册资本(万元)："
                                                >
                                                    {{
                                                        formData.registeredCapital
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="营业执照">
                                                    <span
                                                        @click="preview3()"
                                                        style="
                                                            color: blue;
                                                            cursor: pointer;
                                                            overflow: hidden;
                                                        "
                                                    >
                                                        {{
                                                            formData.businessLicenseOssName
                                                        }}
                                                    </span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="库外单位">
                                                    {{
                                                        formData.isOutOrg == 0
                                                            ? '否'
                                                            : '是'
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="录入机构"
                                                    >{{
                                                        formData.orgName
                                                    }}</el-form-item
                                                >
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="注册地址"
                                                    >{{ formData.address }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="状态">
                                                    {{
                                                        statusLable(
                                                            formData.state
                                                        )
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 委托人 -->
                    <div id="clientCon" class="con">
                        <div class="tabs-title" id="client">委托人</div>
                        <div class="e-table">
                            <el-table
                                :data="aptitudeTable"
                                :max-height="$store.state.tableHeight"
                                @cell-click="cellClick"
                                border
                                style="width: 100%"
                                ref="table"
                                class="table"
                                v-sortTable="{ 'tableData': aptitudeTable, '_this': this, 'ref': 'table' }"
                            >
                                <el-table-column
                                    label="序号"
                                    type="index"
                                    width="60"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="姓名"
                                    prop="name"
                                    width="180"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="手机号"
                                    width="180"
                                    prop="phone"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="身份证号"
                                    width="180"
                                    prop="idCard"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="idCardOssName"
                                    label="身份证附件"
                                    min-width="200"
                                >
                                    <template slot-scope="scope">
                                        <span
                                            @click="preview()"
                                            style="
                                                color: blue;
                                                cursor: pointer;
                                                overflow: hidden;
                                            "
                                        >
                                            {{ scope.row.idCardOssName }}
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="entrustOssName"
                                    label="委托书"
                                    min-width="200"
                                >
                                    <template slot-scope="scope">
                                        <span
                                            @click="preview1()"
                                            style="
                                                color: blue;
                                                cursor: pointer;
                                                overflow: hidden;
                                            "
                                        >
                                            {{ scope.row.entrustOssName }}
                                        </span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                    <!-- 审核历史 -->
                    <div id="accessoryCon" class="con">
                        <div class="tabs-title" id="accessory">审核历史</div>
                        <ComExaHistory
                            :billType="60481"
                            @getAuditHistory="getAuditHistory"
                            :tableData="tableData"
                            ref="ComExaHistory"
                        />
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <ComExaButtons
               v-if="formData.state != -1 && formData.state != 5"
                :auditState="auditState"
                  :state="formData.state"
                :founderId="formData.founderId"
                @exas="exas"
            />
             <el-button
                type="primary"
                v-if="formData.state == 2"
                @click="chengeBtn"
                size="small"
                >变更</el-button
            >
            <el-button @click="cancel" size="small">取消</el-button>
        </div>
    </div>
</template>

<script>
// 审核
import subcontractorChange from '@/api/OutsourcingartyAdmin/subcontractorAdmin/subcontractorChange.js'
import '@/utils/jquery.scrollTo.min'
import { mapMutations } from 'vuex'
// 事实外包方
import correspondentUnit from '@/api/OutsourcingartyAdmin/correspondentUnit/correspondentUnit.js'
//审核历史
import ComExaHistory from '@/components/common/exaHistory.vue'
// 按钮
import ComExaButtons from '@/components/common/exaButtons'
//审核
import examine from '@/api/OutsourcingartyAdmin/subcontractorAdmin/examine.js'
import { showSuccessPop, openAppClient, throttle, showLoading, hideLoading } from '@/utils/common'
// 作废
import { toVoid } from '@/api/OutsourcingartyAdmin/subcontractorAdmin/subcontractor.js'
export default {
    components: {
        ComExaHistory,
        ComExaButtons
    },
    data () {
        return {
            tabsName: 'baseInfo',
            //表单数据
            formData: {
                address: '', //	注册地址
                businessLicenseOss: '', //	营业执照附件主键
                businessLicenseOssName: '', //营业执照
                creditCode: '', //统一信用代码
                deputy: '', //法人
                deputyOss: '', //法人附加主键
                deputyOssName: '', //法人身份附件名字
                id: '', //主键
                idCard: '', //法人身份证
                isOutOrg: '', //是否是库外单位（0 不是 1是)
                orgId: '', //机构id
                orgName: '', //机构名称
                outerName: '', //外包方名称
                registeredCapital: 0, //注册资本
                state: 0, //	单据状态
                type: 0 //外包方类型（0 分包商 1 供应商）
            },
            //类型列表
            typeList: [],
            payTaxesTypeList: [], //纳税类别列表

            firmPerformanceTable: [], //历史业绩数据
            firmPerformanceSend: false, //历史业绩是否验证成功

            isBaseSave: false, //基础是否保存
            alterationTable: [], //历史变更
            auditState: {}, //按钮状态
            newBaseData: {}, //处理过后的基础数据
            //是否为境外单位的单选
            radio: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            billid: '', //单据id
            winEvent: {}, //保存事件，跳转页面的时候，结束事件，优化性能
            lastConHeight: 0, //最后一个区域高度
            errorList: [], //错误标签
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            isIndeterminate: true,
            checkAll: false,
            tableData: [],
            // 事实外包方
            //上传的地址
            uploadUrl: '/oss/uploader',
            accept: '.jpg,jpeg,.png,.pdf',
            bucketName: 'OutsourcingartyAdmin', //模块名
            relationId: '',
            tableRowClass: true, //是否展示组件clss
            aptitudeSend: false, //委托人验证是否通过
            aptitudeTable: [], //委托人
            rowIndex: '',
            // 审核对象
            commit: {
                billId: '', //	单据Id
                billType: 60481, //单据编码
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //	下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '' //审核意见
            }
        }
    },
    computed: {
        // 判断状态
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value == param)
                if (obj !== undefined) {
                    return obj.label
                }
            }
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 102 - this.lastConHeight
        },
        orgCode () {
            return this.$store.state.userInfo.orgInfo.shortCode
        }
    },
    created () {
        this.billid = this.$route.query.billid
        // 历史业绩id
        this.formData.founderName = localStorage.getItem('userName')
        this.formData.founderId = localStorage.getItem('userId')
        this.getBasicData() //获取基础数据
        this.getCurrentUnitInfo() //获取流程按钮
        this.qualificationList()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()
        // 保存所有tabName
        const arr = [
            'baseInfo',
            'client',
            'accessory',
        ]
        this.tabArr = arr
        let $idsTop = []
        const onScroll = () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        }
        this.winEvent.onScroll = onScroll
        window.addEventListener('scroll', this.winEvent.onScroll)
        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        const onResize = () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        }
        this.winEvent.onResize = throttle(onResize, 500)
        window.addEventListener('resize', this.winEvent.onResize)
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    methods: {
        ...mapMutations(['setPopConfirm']),
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('accessoryCon')) {
                    const lastConHeight =
                        document.getElementById('accessoryCon').offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        // 点击标签的方法
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //获取变更基本信息数据
        async getBasicData () {
            let res = await correspondentUnit.getCorrespondentUnitChange({
                id: this.billid
            })
            //处理注册地址
            let data = JSON.parse(res.address).address.join('')
            let data1 = JSON.parse(res.address).detail
            res.address = data + data1
            this.formData = res
        },
        // 委托人列表
        async qualificationList () {
            let data = await correspondentUnit.getCorrespondentUnitChangeDetailed({
                id: this.billid
            })
            if (data.code != 200) {
                this.aptitudeTable = data
            }
        },
        cellClick (row) {
            //是第几行
            this.rowIndex = this.aptitudeTable.findIndex(x => x === row)
        },
        //预览附件
        preview () {
            if (this.aptitudeTable[this.rowIndex].idCardOssImage) {
                window.open(this.aptitudeTable[this.rowIndex].idCardOssImage)
            }
        },
        //委托书预览附件
        preview1 () {
            if (this.aptitudeTable[this.rowIndex].entrustOssImage) {
                window.open(this.aptitudeTable[this.rowIndex].entrustOssImage)
            }
        },
        //基础信息法人身份附件
        preview2 () {
            if (this.formData.deputyOssImage) {
                window.open(this.formData.deputyOssImage)
            }
        },
        //基础信息营业执照
        preview3 () {
            if (this.formData.businessLicenseOssImage) {
                window.open(this.formData.businessLicenseOssImage)
            }
        },
        //点击表格查看
        Examines (row) {
            //点击进入查看页面
            const billid = row.id
            if (row.state === -1 || row.state === 2 || row.state === 5) {
                this.$router.push({
                    path: '/factualOutsourcerChangeShow',
                    query: { billid }
                })
            } else {
                // 根据按钮状态来判断点击编辑进什么页面
                examine
                    .getCurrentUnitInfo({
                        billId: billid,
                        billType: 60481,
                        freeNextUnitIndex: 0,
                        freeNextUser: '',
                        isPass: true,
                        isShareInAudit: true,
                        opinion: ''
                    })
                    .then(res => {
                        this.auditState = res
                        if (this.auditState.canModify) {
                            this.$router.push({
                                path: '/factualOutsourcerChangeEdit',
                                query: { billid }
                            })
                        } else {
                            this.$router.push({
                                path: '/factualOutsourcerChangeShow',
                                query: { billid }
                            })
                        }
                    })
            }
        },
        // 审核
        audit () {
            // 客户端弹窗弹出本地页面
            openAppClient('/exaDialog', '填写审核意见', () => {
                // 审核拿到审核弹窗的意见
                const auditParams = JSON.parse(
                    localStorage.vuex
                ).auditParams
                // 将审核意见赋值给参数传给后端
                examine
                    .audit({
                        billId: this.billid,
                        billType: 60481,
                        freeNextUnitIndex: 0,
                        freeNextUser: '',
                        isPass: auditParams.isPass,
                        isShareInAudit: true,
                        opinion: auditParams.opinion
                    })
                    .then(() => {
                        this.clientPop('suc', '审核成功')
                        // 返回列表
                        this.cancel()
                    })
            }, null, null, null, 'small')
                .catch(() => {
                    this.clientPop('err', '保存失败')
                    this.scorllError()
                })
        },
        //取消按钮
        cancel () {
            this.$router.replace('/FactualOutsourcer')
        },
        // // 审核历史列表查询
        async getAuditHistory () {
            let data = await subcontractorChange.findByIdAuditHistory({
                billId: this.billid,
                billType: 60481,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            })
            this.tableData = data
        },
        //变更按钮
        chengeBtn () {
            let billid = this.billid
            this.$router.push({
                path: '/factualOutsourcerChangeAdd',
                query: { billid }
            })
        },
        // 删除方法
        ctDelete () {
            this.clientPop(
                'info',
                '确定要删除吗？数据删除后不可恢复，请谨慎操作',
                this.delent
            )
        },
        //删除回调
        delent () {
            this.$Ajax
                .httpGet({
                    url: '/outer/supplier/delete',
                    params: {
                        id: this.billid
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    if (res.code == 200) {
                        showSuccessPop('删除成功！')
                        this.isSkip = true
                    }
                    this.$router.replace('/FactualOutsourcer')
                })
        },
        // 撤回
        withdrawChange () {
            this.clientPop('info', '是否确认撤回', this.callbackWithdraw)
        },
        // 撤回确认回调
        async callbackWithdraw () {
            let { code } = await examine.undoAudit({
                billId: this.billid, //单据id
                billType: '60481', //单据类型
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            })
            if (code == 200) {
                showSuccessPop('撤回成功')
                // 返回列表
                this.cancel()
            } else {
                showSuccessPop('撤回失败')
            }
        },
        // 作废
        toVoidChange () {
            this.clientPop('info', '是否确认作废', this.callback)
        },
        // 作废确认回调
        async callback () {
            // 客户端弹窗弹出本地页面
            const auditParams = JSON.parse(localStorage.vuex).auditParams
            openAppClient('/nullifyDialog', '单据作废原因', async () => {
                showLoading()
                await toVoid({
                    billId: this.billid, //单据id
                    billType: '60481', //单据类型
                    nullifyCreated: '',
                    nullifyCreator: '',
                    nullifyCreatorId: '',
                    nullifyDescription: auditParams.nullifyDescription,
                    nullifyReason: auditParams.nullifyReason
                })
                    .catch(() => {
                        this.clientPop('suc', '作废失败')
                    })
                hideLoading()
            })
        },
        // 按钮组件触发事件
        exas (data) {
            switch (data) {
            case 'audit':
                this.audit() //审核
                break
            case 'undoAudit':
                this.withdrawChange() //撤回
                break
            case 'submitCommit':
                this.submit() //提交
                break
            case 'submit':
                this.save() //保存
                break
            case 'nullify':
                this.toVoidChange() //作废
                break
            case 'deleteData':
                this.ctDelete() //删除
                break
            default:
                break
            }
        },
        // // 获取按钮状态
        getCurrentUnitInfo () {
            examine
                .getCurrentUnitInfo({
                    billId: this.billid,
                    billType: 60481,
                    freeNextUnitIndex: 0,
                    freeNextUser: '',
                    isPass: true,
                    isShareInAudit: true,
                    opinion: ''
                })
                .then(res => {
                    this.auditState = res
                })
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}

.el-tab-pane {
    margin-left: -10px;
}
// 境外单位
::v-deep .clearPadding .vxe-cell {
    padding: 0;
}
::v-deep .clearPaddingLeft .vxe-cell {
    padding-left: 0px;
}
::v-deep {
    .main-el-switch {
        position: relative;
        .el-switch__core {
            height: 24px;
            border-radius: 12px;
            &:after {
                left: 4px;
                top: 3px;
            }
        }
        &.el-switch {
            &.is-checked {
                .el-switch__core {
                    &:after {
                        margin-left: -20px;
                        left: 100%;
                    }
                }
            }
        }
        &.is-checked {
            .el-switch__label--left {
                opacity: 0;
            }
            .el-switch__label--right {
                opacity: 1;
            }
        }
        .el-switch__label {
            position: absolute;
            top: 0;
        }
        .el-switch__label--left {
            right: 0;
            color: #999;
            z-index: 1;
            margin-right: 8px;
        }
        .el-switch__label--right {
            left: 0;
            color: #fff;
            opacity: 0;
            margin-left: 8px;
        }
    }
}
</style>
